@tool
class_name FloatingButton
extends FloatingTexture

@export var idle_offset: float = 0.075
@export var hover_offset: float = 0.125
@export var down_offset: float = 0.05

@export var hover_trans_time = 0.2
@export var down_trans_time = 0.05

signal button_down
signal button_up

@onready var _offset_to: float
var _timer: float = 0
var _trans_time: float = -1

var _is_hover: bool = false
var _is_down: bool = false

func _ready() -> void:
	mouse_entered.connect(_mouse_enter)
	mouse_exited.connect(_mouse_exit)
	
	call_deferred("_set_idle")


func _gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed:
				_is_down = true
				button_down.emit()
				_offset_to = down_offset
				_trans_time = down_trans_time
				_timer = 0
			else:
				_is_down = false
				button_up.emit()
				if _is_hover:
					_offset_to = hover_offset
				else:
					_offset_to = idle_offset
				_trans_time = down_trans_time
				_timer = 0
			set_process(true)


func _process(delta: float) -> void:
	if _trans_time <= 0:
		return
	
	if _timer > _trans_time:
		offset = _offset_to
		_trans_time = -1
		set_process(false)
		return
	
	offset = lerpf(offset, _offset_to, _timer / _trans_time)
	_timer += delta


func _mouse_enter():
	_offset_to = hover_offset
	_trans_time = hover_trans_time
	_timer = 0
	_is_hover = true
	set_process(true)


func _mouse_exit():
	if not _is_down:
		_offset_to = idle_offset
	_trans_time = hover_trans_time
	_timer = 0
	_is_hover = false
	set_process(true)


func _set_idle():
	_offset_to = idle_offset
	offset = idle_offset
